package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.admin.ChannelDto;
import com.heima.model.common.dtos.common.PageDto;
import com.heima.model.common.dtos.common.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.mapper.WmChannelMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
* @author Fu319
* @description 针对表【wm_channel(频道信息表)】的数据库操作Service实现
* @createDate 2025-04-02 16:25:21
*/
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel>
    implements WmChannelService{
    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Override
    public ResponseResult pageList(PageDto pageDto) {
        if(pageDto ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Page<WmChannel> page = new Page<>(pageDto.getPage(), pageDto.getSize());
        LambdaQueryWrapper<WmChannel> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(pageDto.getName())){
            wrapper.like(WmChannel::getName, pageDto.getName());
        }
        wrapper.orderByDesc(WmChannel::getCreatedTime);
        Page<WmChannel> pageData = wmChannelMapper.selectPage(page, wrapper);
        List<WmChannel> records = pageData.getRecords();
        return ResponseResult.okResult(pageData.getRecords());
    }

    @Override
    public ResponseResult saveChannel(ChannelDto channelDto) {
        //检验参数
        if(channelDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //频道名称必须唯一
        List<WmChannel> wmChannels = wmChannelMapper.selectList(null);
        for (WmChannel wmChannel : wmChannels) {
            if(channelDto.getName().equals(wmChannel.getName())){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"该频道已存在");
            }
        }
        WmChannel wmChannel = new WmChannel();
        BeanUtils.copyProperties(channelDto, wmChannel);
        //设置频道为默认频道
        wmChannel.setIsDefault(1);
        if(channelDto.getStatus().equals(true)){
            wmChannel.setStatus(1);
        }else{
            wmChannel.setStatus(0);
        }
        wmChannel.setCreatedTime(new Date());
        wmChannelMapper.insert(wmChannel);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}




